package com.geeklan.smart.data.remote.tcp;

import com.geeklan.base.utils.MLog;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class TCPClient {
    private static final int SERVER_PORT = 8869;
    private static final String SERVER_IP = "192.168.25.1";
    private Socket socket;
    public boolean isConnected(){
        if(socket != null)
            return socket.isConnected();
        return false;
    }
    private BufferedReader reader;
    private OutputStream outputStream;
    private final OnMessageReceivedListener messageListener;
    private final OnConnectionStatusListener connectionListener;

    public TCPClient(OnMessageReceivedListener messageListener,
                     OnConnectionStatusListener connectionListener) {
        this.messageListener = messageListener;
        this.connectionListener = connectionListener;
        connect();
    }

    // 连接服务器
    private void connect() {
        new Thread(() -> {
            try {
                socket = new Socket(SERVER_IP, SERVER_PORT);
                if (socket.isConnected()) {
                    outputStream = socket.getOutputStream();
                    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    // 开启接收消息线程
                    receiveMessages();

                    if (connectionListener != null) {
                        connectionListener.onConnected(1);
                    }
                }
            } catch (Exception e) {
                if (connectionListener != null) {
                    connectionListener.onConnectionError("Connection error: " + e.getMessage());
                }
            }
        }).start();
    }

    // 发送消息到服务器
    public void sendMessage(String message) {
        new Thread(() -> {
            try {
                MLog.i("******** tcp send message : " + message);
                if (socket != null && socket.isConnected() && outputStream != null) {
                    outputStream.write(message.getBytes(StandardCharsets.US_ASCII));
                    outputStream.write("".getBytes(StandardCharsets.US_ASCII));
                    outputStream.flush();
                } else {
                    if (connectionListener != null) {
                        connectionListener.onConnectionError("Socket is not connected");
                    }
                }
            } catch (Exception e) {
                if (connectionListener != null) {
                    connectionListener.onConnectionError("Error sending message: " + e.getMessage());
                }
            }
        }).start();
    }

    // 接收消息
    private void receiveMessages() {
        new Thread(() -> {
            try {
                String message;
                while ((message = reader.readLine()) != null) {
                    if (messageListener != null) {
                        messageListener.onMessageReceived("Received from server: " + message);
                    }
                }
            } catch (Exception e) {
                if (connectionListener != null) {
                    connectionListener.onConnectionError("Error receiving message: " + e.getMessage());
                }
            }
        }).start();
    }

    // 关闭连接
    public void disconnect() {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 消息回调接口
    public interface OnMessageReceivedListener {
        void onMessageReceived(String message);
    }

    // 连接状态回调接口
    public interface OnConnectionStatusListener {
        void onConnected(int status);

        void onConnectionError(String error);
    }
}


